package cn.community.system.service.impl;

import cn.community.system.domain.Activity;
import cn.community.system.domain.ActivityRecord;
import cn.community.system.domain.Association;
import cn.community.system.domain.Member;
import cn.community.system.exception.LogicException;
import cn.community.system.mapper.ActivityMapper;
import cn.community.system.mapper.ActivityRecordMapper;
import cn.community.system.mapper.AssociationMapper;
import cn.community.system.mapper.MemberMapper;
import cn.community.system.query.ActivityQuery;
import cn.community.system.query.QueryObject;
import cn.community.system.service.IActivityService;
import cn.community.system.util.AssertUtils;
import cn.community.system.util.UserContext;
import cn.community.system.vo.ActivityVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ActivityServiceImpl implements IActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private AssociationMapper associationMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private ActivityRecordMapper activityRecordMapper;

    @Override
    public void delete(Long id) {
        Activity activity = activityMapper.selectByPrimaryKey(id);
        Date endTime = activity.getEndTime();
        endTime.setMinutes(endTime.getMinutes() + 20);
        if(activity.getIsAgree() == Activity.PASS_YES &&  endTime.getTime() > new Date().getTime()){
            // 减少社团的活动个数和总时长
            Association association = associationMapper.selectByPrimaryKey(activity.getSponsorId());
            association.setActivityNumber(association.getActivityNumber()-1);
            association.setDay(association.getDay()- activity.getAllTime()/24);
            associationMapper.updateActivityNumberAndDay(association);

            // 删除该活动下报名记录
            activityRecordMapper.deleteByActivityId(activity.getId());
            // ...
        }
        activityMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Activity activity) {
        // 参数校验
        AssertUtils.hasLength(activity.getTitle(),"活动标题不能为空！");
        if(activity.getPerson() <= 0){
            throw new LogicException("所需人数必须大于0！");
        }
        if (activity.getApplyStartTime() == null || activity.getApplyEndTime() == null){
            throw new LogicException("报名时间必填！");
        }
        if (activity.getStartTime() == null || activity.getEndTime() == null){
            throw new LogicException("活动时间必填！");
        }
//        if (activity.getApplyStartTime().getTime() <= new Date().getTime() || activity.getApplyEndTime().getTime() <= new Date().getTime()){
//            throw new LogicException("请输入正确的报名时间！");
//        }
//        if (activity.getStartTime().getTime() <= new Date().getTime() || activity.getEndTime().getTime() <= new Date().getTime()){
//            throw new LogicException("请输入正确的活动时间！");
//        }
        if (activity.getApplyStartTime().getTime() >= activity.getApplyEndTime().getTime()){
            throw new LogicException("请输入正确的报名结束时间！");
        }
        if (activity.getStartTime().getTime() >= activity.getEndTime().getTime()){
            throw new LogicException("请输入正确的活动结束时间！");
        }
        AssertUtils.hasLength(activity.getSite(),"活动地点不能为空！");
        AssertUtils.hasLength(activity.getDutyName(),"负责人不能为空！");
        AssertUtils.hasLength(activity.getMobile(),"负责人联系方式不能为空！");
        // 主办方
        Association association = associationMapper.selectByName(activity.getSponsor());
        if (association != null){
            activity.setSponsorId(association.getId());
        }else {
            throw new LogicException("请输入正确的主办方名字！");
        }
        // 活动总时长
        Date startTime = activity.getStartTime();
        Date endTime = activity.getEndTime();
        Long time = endTime.getTime() - startTime.getTime();
        Double allTime = (time+0.0)/3600000;
        activity.setAllTime(allTime);
        // 是否需要管理员审核
        if(activity.getIsAgree() == Activity.NEED_NO){
            activity.setIsAgree(Activity.PASS_YES);
            activity.setCreateTime(new Date());
        }
        if(activity.getImgUrl() == ""){
            activity.setImgUrl(null);
        }
        activityMapper.insert(activity);
    }

    @Override
    public void save2(Activity activity) {
        // 参数校验
        AssertUtils.hasLength(activity.getTitle(),"活动标题不能为空！");
        if(activity.getPerson() <= 0){
            throw new LogicException("所需人数必须大于0！");
        }
        if (activity.getApplyStartTime() == null || activity.getApplyEndTime() == null){
            throw new LogicException("报名时间必填！");
        }
        if (activity.getStartTime() == null || activity.getEndTime() == null){
            throw new LogicException("活动时间必填！");
        }
//        if (activity.getApplyStartTime().getTime() <= new Date().getTime() || activity.getApplyEndTime().getTime() <= new Date().getTime()){
//            throw new LogicException("请输入正确的报名时间！");
//        }
//        if (activity.getStartTime().getTime() <= new Date().getTime() || activity.getEndTime().getTime() <= new Date().getTime()){
//            throw new LogicException("请输入正确的活动时间！");
//        }
        if (activity.getApplyStartTime().getTime() >= activity.getApplyEndTime().getTime()){
            throw new LogicException("请输入正确的报名结束时间！");
        }
        if (activity.getStartTime().getTime() >= activity.getEndTime().getTime()){
            throw new LogicException("请输入正确的活动结束时间！");
        }
        AssertUtils.hasLength(activity.getSite(),"活动地点不能为空！");
        AssertUtils.hasLength(activity.getDutyName(),"负责人不能为空！");
        AssertUtils.hasLength(activity.getMobile(),"负责人联系方式不能为空！");
        // 主办方
        Association association = UserContext.getCurrentAssociation();
        activity.setSponsor(association.getUsername());
        activity.setSponsorId(association.getId());

        // 活动总时长
        Date startTime = activity.getStartTime();
        Date endTime = activity.getEndTime();
        Long time = endTime.getTime() - startTime.getTime();
        Double allTime = (time+0.0)/3600000;
        activity.setAllTime(allTime);
        // 是否需要管理员审核
        if(activity.getIsAgree() == Activity.NEED_NO){
            activity.setIsAgree(Activity.PASS_YES);
            activity.setCreateTime(new Date());
        }
        if(activity.getImgUrl() == ""){
            activity.setImgUrl(null);
        }
        activityMapper.insert(activity);
    }

    @Override
    public Activity get(Long id) {
        return activityMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Activity> listAll() {
        return activityMapper.selectAll();
    }

    @Override
    public void update(Activity activity) {
        // 参数校验
        AssertUtils.hasLength(activity.getTitle(),"活动标题不能为空！");
        if(activity.getPerson() <= 0){
            throw new LogicException("所需人数必须大于0！");
        }
        if (activity.getApplyStartTime() == null || activity.getApplyEndTime() == null){
            throw new LogicException("报名时间必填！");
        }
        if (activity.getStartTime() == null || activity.getEndTime() == null){
            throw new LogicException("活动时间必填！");
        }
        if (activity.getApplyStartTime().getTime() >= activity.getApplyEndTime().getTime()){
            throw new LogicException("请输入正确的报名结束时间！");
        }
        if (activity.getStartTime().getTime() >= activity.getEndTime().getTime()){
            throw new LogicException("请输入正确的活动结束时间！");
        }
        AssertUtils.hasLength(activity.getSite(),"活动地点不能为空！");
        AssertUtils.hasLength(activity.getDutyName(),"负责人不能为空！");
        AssertUtils.hasLength(activity.getMobile(),"负责人联系方式不能为空！");
        // 主办方
        Association association = associationMapper.selectByName(activity.getSponsor());
        if (association != null){
            activity.setSponsorId(association.getId());
        }else {
            throw new LogicException("请输入正确的主办方名字！");
        }

        // 活动总时长
        Date startTime = activity.getStartTime();
        Date endTime = activity.getEndTime();
        Long time = endTime.getTime() - startTime.getTime();
        Double allTime = (time+0.0)/3600000;
        activity.setAllTime(allTime);
        // 状态
        if(activity.getIsAgree() != null){
            if(activity.getIsAgree() == Activity.PASS_YES){
                activity.setIsAgree(Activity.PASS_YES);
                activity.setCreateTime(new Date());
            }
        }
        if(activity.getImgUrl() == ""){
            activity.setImgUrl(null);
        }
        // 测试：
        if(endTime.getTime() <= new Date().getTime() && activity.getIsAgree() == Activity.PASS_YES){
            this.isEnd(activity);
        }
        activityMapper.updateByPrimaryKey(activity);
    }

    @Override
    public void update2(Activity activity) {
        // 参数校验
        AssertUtils.hasLength(activity.getTitle(),"活动标题不能为空！");
        if(activity.getPerson() <= 0){
            throw new LogicException("所需人数必须大于0！");
        }
        if (activity.getApplyStartTime() == null || activity.getApplyEndTime() == null){
            throw new LogicException("报名时间必填！");
        }
        if (activity.getStartTime() == null || activity.getEndTime() == null){
            throw new LogicException("活动时间必填！");
        }
        if (activity.getApplyStartTime().getTime() >= activity.getApplyEndTime().getTime()){
            throw new LogicException("请输入正确的报名结束时间！");
        }
        if (activity.getStartTime().getTime() >= activity.getEndTime().getTime()){
            throw new LogicException("请输入正确的活动结束时间！");
        }
        AssertUtils.hasLength(activity.getSite(),"活动地点不能为空！");
        AssertUtils.hasLength(activity.getDutyName(),"负责人不能为空！");
        AssertUtils.hasLength(activity.getMobile(),"负责人联系方式不能为空！");
        // 主办方
        Association association = UserContext.getCurrentAssociation();
        activity.setSponsor(association.getUsername());
        activity.setSponsorId(association.getId());
        // 活动总时长
        Date startTime = activity.getStartTime();
        Date endTime = activity.getEndTime();
        Long time = endTime.getTime() - startTime.getTime();
        Double allTime = (time+0.0)/3600000;
        activity.setAllTime(allTime);
        if(activity.getImgUrl() == ""){
            activity.setImgUrl(null);
        }

        // 测试：
        if(endTime.getTime() <= new Date().getTime() && activity.getIsAgree() == Activity.PASS_YES){
            this.isEnd(activity);
        }
        activityMapper.updateByPrimaryKey(activity);
    }

    // 编辑活动自动结束后，活动时长的统计
    private void isEnd(Activity activity) {
        // 1、活动结束，统计社团每年的活动总个数和总天数，以及学生获得的活动时长和次数增加
        Double allTime = activity.getAllTime();
        Long sponsorId = activity.getSponsorId();
        // B、获取活动的时长，设置社团每年的活动总个数和总天数
        Association association = associationMapper.selectByPrimaryKey(sponsorId);
        System.out.println("之前的社团每年的活动总个数:"+association.getActivityNumber()+"，总天数："+association.getDay());
        association.setActivityNumber(association.getActivityNumber()+1);
        association.setDay(association.getDay() + allTime/24);
        System.out.println("社团每年的活动总个数:"+association.getActivityNumber()+"，总天数："+association.getDay());
        associationMapper.updateActivityNumberAndDay(association);

        // C、获取报名该活动的学生，设置学生的活动时长和次数
        List<ActivityRecord> activityRecord = activityRecordMapper.getByApplySuccess(activity.getId());
        for (ActivityRecord record : activityRecord) {
            Long applicantId = record.getApplicantId();
            Member member = memberMapper.selectByPrimaryKey(applicantId);
            System.out.println("学号："+member.getNumber()+"，"+member.getUsername()+"的活动总个数:"+member.getActivities()+"，总时长："+member.getActivityTime());
            member.setActivities(member.getActivities() + 1);
            member.setActivityTime(member.getActivityTime() + allTime);
            memberMapper.updateActivitiesAndTime(member);
            System.out.println("学号："+member.getNumber()+"，"+member.getUsername()+"的活动总个数:"+member.getActivities()+"，总时长："+member.getActivityTime());
        }
    }

    public PageInfo query(QueryObject qo) {
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"id desc");
        //查询结果集
        List<Activity> list = activityMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public PageInfo queryAssociation(ActivityQuery qo) {
        Association association = UserContext.getCurrentAssociation();
        qo.setAssoId(association.getId());

        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"id desc");
        //查询结果集
        List<Activity> list = activityMapper.selectForAssociation(qo);
        return new PageInfo(list);
    }

    public PageInfo queryMember(ActivityQuery qo) {
        //使用分页插件,传入当前页,每页显示数量（按发布时间倒序排序）
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"createTime desc");
        //查询结果集
        List<ActivityVo> list = activityMapper.selectForMemberList(qo);
        return new PageInfo(list);
    }

    @Override
    public void batchUpdate(Integer isAgree,Long[] ids) {
        for (Long id : ids) {
            activityMapper.batchUpdate(isAgree,id);
        }
    }

    @Override
    public List<Activity> listOwnAssociation(Long id) {
        List<Activity> activities = activityMapper.listOwnAssociation(id);
        return activities;
    }

    @Override
    public void passOne(Long id, Integer isAgree) {
        Date createTime = null;
        if(isAgree == Activity.PASS_YES){
            createTime = new Date();
        }
        activityMapper.passOne(id,createTime,isAgree);
    }

    @Override
    public List<Activity> getByTime(Date old, Date now) {
        return activityMapper.getByTime(old,now);
    }

}
